package com.webinsky.publish.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webinsky.common.proj.BookMode;
import com.webinsky.common.proj.Lang;
import com.webinsky.common.utils.DateUtils;
import com.webinsky.publish.domain.MisVersion;
import com.webinsky.publish.persist.dao.BookPublishMapper;
import com.webinsky.publish.persist.entity.BookPublish;
import com.webinsky.publish.service.BookPublishManagement;

@Service
public class BookPublishManagementImpl implements BookPublishManagement {
	@Autowired
	private BookPublishMapper publishDao;
	
	private BookPublish convert(MisVersion version){
		BookPublish publish = new BookPublish();
		publish.setBookId(version.getBookMode().getId());
		publish.setFileName(version.getFileName());
		publish.setLanguage(version.getLanguage());
		publish.setPublishUserId(version.getAuthorId());
		publish.setVersion(version.getVersionName());
		return publish;
	}
	
	private MisVersion convert(BookPublish bookPublish){
		MisVersion version = new MisVersion();
		version.setAuthorId(bookPublish.getPublishUserId());
		version.setBookMode(BookMode.parse(bookPublish.getBookId()));
		version.setFileName(bookPublish.getFileName());
		version.setId(bookPublish.getId());
		version.setLanguage(bookPublish.getLanguage());
		version.setVersionDate(DateUtils.format(bookPublish.getPublishDate()));
		version.setVersionName(bookPublish.getVersion());
		return version;
	}
	
	
	@Override
	public void publishVersion(MisVersion version) {
		if ( version != null ){
			BookPublish bookPublish = convert(version);
			publishDao.insert(bookPublish);
		}
	}

	@Override
	public List<MisVersion> getVersion(BookMode bookMode, Lang lang) {
		List<MisVersion> versions = new ArrayList<>();
		if ( bookMode != null && lang != null ){
			List<BookPublish> publisher = publishDao.selectByBookIdAndLanguage(bookMode.getId(), lang.getLang());
			publisher.forEach(e -> {
				versions.add(convert(e));
			});
		}
		return versions;
	}

}
